import { marked } from 'marked';

export default {
    data() {
        return {
            currentTab: 'deepseek', // 默认选中首页
            isCenterActive: false,
            messages: [], // 聊天消息列表
            inputMessage: '', // 输入框内容
            scrollTop: 0,
            apiKey: 'sk-fa1bd3aedb564433a58e22a1dffacebd',
            baseUrl: 'https://api.deepseek.com/v1/chat/completions',
            showSidebar: false,
            chatHistory: [],
            currentChatId: null, // 添加当前对话ID
            isDeepSearchEnabled: false,
            isLoading: false, // 添加加载状态
            // 添加marked配置
            markedOptions: {
                breaks: true, // 支持换行
                gfm: true, // 支持GitHub风格的markdown
            }
        }
    },
    onShow() {
        // 进入页面时设置为激活状态
        this.isCenterActive = true;
    },
    onHide() {
        // 离开页面时重置状态
        this.isCenterActive = false;
    },
    methods: {
        // 切换标签页
        switchTab(tab) {
            this.isCenterActive = false; // 切换标签页时重置状态
            this.currentTab = tab;
            switch(tab) {
                case 'home':
                    uni.redirectTo({
                        url: '/pages/index/index',
                        animationType: 'pop-in',
                        animationDuration: 200
                    });
                    break;
                case 'notify':
                    uni.redirectTo({
                        url: '/pages/notify/notify',
                        animationType: 'pop-in',
                        animationDuration: 200
                    });
                    break;
                case 'control':
                    uni.redirectTo({
                        url: '/pages/control/control',
                        animationType: 'pop-in',
                        animationDuration: 200
                    });
                    break;
                case 'setting':
                    uni.redirectTo({
                        url: '/pages/setting/setting',
                        animationType: 'pop-in',
                        animationDuration: 200
                    });
                    break;
            }
        },
        // 获取图标路径
        getTabIcon(tab) {
            const baseUrl = '../../static/';
            return this.currentTab === tab ?
                `${baseUrl}${tab}-active.png` :
                `${baseUrl}${tab}.png`;
        },
        // 发送消息
        async sendMessage() {
            if (this.inputMessage.trim() === '') {
                uni.showToast({
                    title: '请输入消息内容',
                    icon: 'none'
                });
                return;
            }

            const userMessage = {
                role: 'user',
                content: this.inputMessage
            };

            this.messages.push(userMessage);
            this.inputMessage = '';
            this.isLoading = true;

            try {
                // 根据深度思考状态选择模型
                const modelName = this.isDeepSearchEnabled ? 'deepseek-reasoner' : 'deepseek-chat';

                const response = await uni.request({
                    url: this.baseUrl,
                    method: 'POST',
                    header: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${this.apiKey}`
                    },
                    data: {
                        messages: this.messages,
                        model: modelName,
                        temperature: 0.7,
                        max_tokens: 2000,
                        stream: false
                    }
                });

                if (response.statusCode !== 200) {
                    throw new Error(`请求失败: ${response.statusCode}`);
                }

                if (response.data && response.data.choices && response.data.choices[0]) {
                    const aiMessage = {
                        role: 'assistant',
                        content: response.data.choices[0].message.content
                    };
                    this.messages.push(aiMessage);

                    // 保存对话历史
                    if (this.currentChatId) {
                        const chatIndex = this.chatHistory.findIndex(chat => chat.id === this.currentChatId);
                        if (chatIndex !== -1) {
                            this.chatHistory[chatIndex].messages = [...this.messages];
                            // 修改这里的key
                            uni.setStorageSync('deepseek_history', JSON.stringify(this.chatHistory));
                        }
                    }
                } else {
                    throw new Error('API返回数据格式错误');
                }
            } catch (error) {
                console.error('API请求错误:', error);
                uni.showToast({
                    title: error.message || '发送消息失败',
                    icon: 'none',
                    duration: 2000
                });

                // 移除失败的消息
                this.messages.pop();
            } finally {
                this.isLoading = false;
                this.$nextTick(() => {
                    this.scrollToBottom();
                });
            }
        },
        // 滚动到底部
        scrollToBottom() {
            setTimeout(() => {
                const query = uni.createSelectorQuery().in(this);
                query.select('.chat-container').boundingClientRect(data => {
                    this.scrollTop = data.height * 2;
                }).exec();
            }, 100);
        },
        // 加载更多消息
        loadMoreMessages() {
            // 这里可以实现加载历史消息的逻辑
        },
        toggleSidebar() {
            this.showSidebar = !this.showSidebar;
        },
        newChat() {
            // 保存当前对话到历史记录
            if (this.messages.length > 0) {
                const chatId = Date.now().toString();
                // 获取最后一个用户消息作为标题
                const lastUserMessage = [...this.messages]
                    .reverse()
                    .find(msg => msg.role === 'user');

                const title = lastUserMessage ?
                    (lastUserMessage.content.length > 20 ?
                        lastUserMessage.content.substring(0, 20) + '...' :
                        lastUserMessage.content) :
                    '新对话';

                this.chatHistory.unshift({
                    id: chatId,
                    title: title,
                    time: new Date().toLocaleString(),
                    messages: [...this.messages]
                });

                // 保存到本地存储
                try {
                    uni.setStorageSync('deepseek_history', JSON.stringify(this.chatHistory));
                } catch (error) {
                    console.error('保存历史记录失败:', error);
                }
            }

            // 清空当前对话
            this.messages = [];
            this.currentChatId = null;

            // 滚动到顶部
            this.scrollTop = 0;

            // 关闭侧边栏
            this.showSidebar = false;
        },
        onLoad() {
            try {
                const history = uni.getStorageSync('deepseek_history');
                if (history) {
                    this.chatHistory = JSON.parse(history);
                }
            } catch (error) {
                console.error('加载历史记录失败:', error);
            }
        },
        // 切换对话
        switchChat(chatId) {
            // 保存当前对话
            if (this.messages.length > 0) {
                const currentChat = this.chatHistory.find(chat => chat.id === this.currentChatId);
                if (currentChat) {
                    currentChat.messages = [...this.messages];
                    // 修改这里的key
                    uni.setStorageSync('deepseek_history', JSON.stringify(this.chatHistory));
                }
            }

            // 加载选中的对话
            const selectedChat = this.chatHistory.find(chat => chat.id === chatId);
            if (selectedChat) {
                this.currentChatId = chatId;
                this.messages = [...selectedChat.messages];
                this.showSidebar = false; // 关闭侧边栏

                // 滚动到底部
                this.$nextTick(() => {
                    this.scrollToBottom();
                });
            }
        },
        toggleDeepSearch() {
            this.isDeepSearchEnabled = !this.isDeepSearchEnabled;
        },
        // 修改markdown渲染方法
        renderMarkdown(text) {
            try {
                // 配置marked选项
                marked.setOptions({
                    renderer: new marked.Renderer(),
                    gfm: true,
                    breaks: true,
                    sanitize: true, // 消毒HTML标签
                    smartLists: true,
                    smartypants: true
                });

                // 渲染markdown
                const html = marked(text);

                // 转换为小程序支持的节点格式
                return html.replace(/<code>/g, '<code class="markdown-code">')
                    .replace(/<pre>/g, '<pre class="markdown-pre">')
                    .replace(/<blockquote>/g, '<blockquote class="markdown-quote">')
                    .replace(/<table>/g, '<table class="markdown-table">')
                    .replace(/<th>/g, '<th class="markdown-th">')
                    .replace(/<td>/g, '<td class="markdown-td">')
                    .replace(/<ul>/g, '<ul class="markdown-ul">')
                    .replace(/<ol>/g, '<ol class="markdown-ol">')
                    .replace(/<li>/g, '<li class="markdown-li">')
                    .replace(/<h([1-6])>/g, '<h$1 class="markdown-h$1">');
            } catch (error) {
                console.error('Markdown渲染错误:', error);
                return text;
            }
        },
        parseMessage(text) {
            const blocks = [];
            const codeRegex = /```(\w*)\n([\s\S]*?)```/g;
            let lastIndex = 0;
            let match;

            while ((match = codeRegex.exec(text)) !== null) {
                // 添加代码块之前的文本
                if (match.index > lastIndex) {
                    blocks.push({
                        type: 'text',
                        content: text.slice(lastIndex, match.index)
                    });
                }

                // 处理代码高亮
                let code = match[2].trim();
                const language = match[1] || 'text';

                // 处理代码高亮
                let highlightedCode = code;

                // 处理HTML标签
                highlightedCode = highlightedCode.replace(/(&lt;|<)(\/?[a-zA-Z][^>]*?)(&gt;|>)/g,
                    '<span class="code-tag">$1$2$3</span>');

                // 处理HTML属性
                highlightedCode = highlightedCode.replace(/(\s[a-zA-Z-]+)=/g,
                    '<span class="code-attr">$1</span>=');

                // 处理关键字
                const keywords = ['class', 'public', 'private', 'static', 'void', 'function', 'const', 'let', 'var',
                    'if', 'else', 'for', 'while', 'do', 'switch', 'case', 'break', 'continue', 'return', 'try',
                    'catch', 'finally', 'throw', 'new', 'delete', 'typeof', 'instanceof'];
                keywords.forEach(keyword => {
                    const regex = new RegExp(`\\b${keyword}\\b`, 'g');
                    highlightedCode = highlightedCode.replace(regex,
                        `<span class="code-keyword">${keyword}</span>`);
                });

                // 处理类型
                const types = ['string', 'number', 'boolean', 'object', 'array', 'null', 'undefined',
                    'String', 'Number', 'Boolean', 'Object', 'Array', 'Function', 'Symbol', 'Promise'];
                types.forEach(type => {
                    const regex = new RegExp(`\\b${type}\\b`, 'g');
                    highlightedCode = highlightedCode.replace(regex,
                        `<span class="code-type">${type}</span>`);
                });

                // 处理字符串
                highlightedCode = highlightedCode.replace(/(['"])(.*?)\1/g,
                    '<span class="code-string">$1$2$1</span>');

                // 处理数字
                highlightedCode = highlightedCode.replace(/\b(\d+(\.\d+)?)\b/g,
                    '<span class="code-number">$1</span>');

                // 处理注释
                highlightedCode = highlightedCode.replace(/(\/\/[^\n]*|\/\*[\s\S]*?\*\/)/g,
                    '<span class="code-comment">$1</span>');

                // 处理函数调用
                highlightedCode = highlightedCode.replace(/\b([a-zA-Z_]\w*)\s*\(/g,
                    '<span class="code-function">$1</span>(');

                // 处理变量
                highlightedCode = highlightedCode.replace(/\b([a-zA-Z_]\w*)\b(?!\()/g,
                    '<span class="code-variable">$1</span>');

                blocks.push({
                    type: 'code',
                    language: language,
                    content: highlightedCode
                });

                lastIndex = match.index + match[0].length;
            }

            // 添加最后一段文本
            if (lastIndex < text.length) {
                blocks.push({
                    type: 'text',
                    content: text.slice(lastIndex)
                });
            }

            return blocks;
        },
        copyCode(code) {
            uni.setClipboardData({
                data: code,
                success: () => {
                    uni.showToast({
                        title: '代码已复制',
                        icon: 'none'
                    });
                }
            });
        },
        handleEnterPress(e) {
            // 如果按下的是回车键且没有按住shift键
            if (e.keyCode === 13 && !e.shiftKey) {
                e.preventDefault(); // 阻止默认换行
                this.sendMessage(); // 发送消息
            }
        }
    }
}